<template>
  <el-container>
    <el-main class="main-bg">
      <div id="printArea">
        <div class="printArea-main">
          <div id="excelArea" class="form-list-card">
            <Form :form="form" :table-header-data="tableHeader" name="一、经办人" />
          </div>
          <div class="form-list-card">
            <Form :form="form" :table-header-data="tableHeader" name="二、记账" />
          </div>
          <div class="form-list-card">
            <Form :form="form" :table-header-data="tableHeader" name="三、存根" />
          </div>
        </div>
      </div>
      <div class="footer">
        <el-button @click="onBack">取消</el-button>
        <el-button v-print="printObj" type="primary">打印</el-button>
        <el-button
          icon="el-icon-download"
          type="primary"
          @click="exportData"
        >导出
        </el-button>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import addTable from '@/mixins/addtable'
import { getInBoundDetail } from './api'
import { parseTime } from '@/utils'
import { onPrint } from '@/utils/print'
import Form from './form'

export default {
  name: 'Inbound',
  components: {
    Form
  },
  mixins: [addTable],
  data() {
    return {
      tableHeader: [],
      form: {},
      printObj: {
        id: 'printArea',
        // popTitle: '打印', // 打印配置页上方标题
        extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {
        }, // 预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {
        }, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {
        }, // 开启打印前的回调事件
        openCallback() {
        }, // 调用打印之后的回调事件
        closeCallback() {
        }, // 关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: '',
      }
    }
  },
  async created() {
    const _this = this
    this.tableHeader = [
      {
        prop: 'index',
        label: '编号',
        sortable: false,
        overflow: false,
        align: 'center',
        width: 80
      },
      {
        prop: 'inBoundName',
        label: '名称',
        sortable: false,
        overflow: false,
        minWidth: 170,
        align: 'center',
        render: (h, vm) => {
          if (typeof vm.index === 'number') {
            return <span>{ vm.inBoundName }</span>
          } else {
            return <div class='inBoundMoney'><span>{ vm.inBoundName }</span>{ ' ¥' + _this.form.totalAmount }</div>
          }
        }
      },
      {
        prop: 'inBoundType',
        label: '规格',
        sortable: false,
        overflow: false,
        align: 'center',
        width: 120,
      },
      {
        prop: 'inBoundUnitName',
        label: '单位',
        sortable: false,
        overflow: false,
        align: 'center',
        width: 80
      },
      {
        prop: 'inBoundNum',
        label: '入库数量',
        sortable: false,
        overflow: false,
        align: 'center',
      },
      {
        prop: 'inBoundPrice',
        label: '单价',
        sortable: false,
        overflow: false,
        align: 'center',
        width: 100
      },
      {
        prop: 'inBoundMoney',
        label: '金额',
        sortable: false,
        overflow: false,
        align: 'center'
      },
      {
        prop: 'remark',
        label: '备注',
        sortable: false,
        overflow: false,
        align: 'center',
        width: 200
      }
    ]
    const id = this.$route.query.id
    this.getTableData(id)
  },

  methods: {
    exportData() {
      const time = parseTime(this.form.createdTime)
      const excelName = `入库单-${time}.xlsx`;
      const xlsxParam = { raw: true };// 转换成excel时，使用原始的格式
      // 克隆节点
      const tables = document.getElementById("excelArea").cloneNode(true);
      // 判断是否为固定列，解决（为固定列时，会重复生成表格）
      if (tables.querySelector('.el-table__fixed') !== null) {
        tables.removeChild(tables.querySelector('.el-table__fixed'))
      }
      // 在这之前可以修改tables添加东西
      const table_book = this.$XLSX.utils.table_to_book(tables, xlsxParam);
      const table_write = this.$XLSX.write(table_book, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      // 在这可以操作table_write设置导出表格样式
      try {
        this.$FileSaver.saveAs(
           new Blob([table_write], { type: "application/octet-stream" }),
           excelName
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, table_write);
      }
      return table_write;
    },
    onBack() {
      this.$router.push('inBound')
    },
    getTableData(id) {
      this.loading = true
      getInBoundDetail({ id })
         .then((res) => {
           if (!res) return
           const { data } = res
           setTimeout(() => {
             this.loading = false
             const dateTime = parseTime(data.dateTime, '{y}-{m}-{d}')
             this.form = {
               ...data,
               year: dateTime.split('-')[0],
               month: dateTime.split('-')[1],
               day: dateTime.split('-')[2],
             }
             this.form.subTable.forEach((item, index) => {
               item.index = index + 1
             })
             this.form.subTable.push({
               index: '合计金额',
               inBoundName: '(大写)' + data.totalAmountChinese
             })
           }, 500)
         })
         .catch((err) => {
           console.log('TCL: getTableData -> err', err)
         })
    }
  }
}
</script>
<style lang="scss">
@page {
  size: auto;
  margin: 3mm;
}

//@media print {
//  html {
//    margin: 0px;
//  }
//
//  #printArea {
//    margin: 0 30px;
//    padding-bottom: 0;
//  }
//  .printArea-main {
//    display: flex;
//    flex-direction: column;
//    //justify-content: space-between;
//    //height: calc(100vh - 18mm);
//
//    .form-list-card {
//      padding: 0;
//      height: calc((100vh - 18mm) / 3);
//      box-sizing: border-box;
//      display: flex;
//      align-items: center;
//    }
//  }
//}

#printArea {
  margin: 0 20px;

  .el-table {
    border-bottom: 2px solid #333;
    border-right: 2px solid #333;
    margin: 0 auto;

    .cell {
      line-height: 14px !important;
      padding: 0 2px !important;
    }

    th, td {

      .cell {
        font-size: 13px;
      }
    }
  }

  .el-table--small .el-table__cell {
    padding: 4px 0 !important;
  }

  .el-table th {
    border: 2px solid #333;
    border-right: none;
    border-bottom: none;
  }

  .el-table td {
    border: 2px solid #333;
    border-right: none;
    border-bottom: none;
  }
}

.printArea-main {
  display: flex;
  flex-direction: column;
}

.form-list-card {
  width: 1000px;
  font-size: 14px;
  height: 12.5cm;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  margin: 0 auto;

  &:last-child {
    border-bottom: none;
  }

  .form-list {
    width: 100%;

    .title {
      width: 100%;
      text-align: center;
      font-size: 30px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .data {
      display: flex;

      .form-left {
        //flex: 0.9;
        flex: 1;
      }

      .form-right {
        width: 50px;
        display: flex;
        align-items: center;
        justify-content: center;

        .vertical-text {
          writing-mode: vertical-rl; /* 从右向左的竖排文字 */
          text-orientation: mixed; /* 混合排列，可以使得中文正常显示 */
          white-space: nowrap; /* 防止文字换行 */
        }
      }

      .data-table {
        margin: 10px 0;
      }

      .el-col {
        display: flex;
        align-items: center;

        span {
          display: inline-block;
          white-space: nowrap;
          margin: 0 6px;
        }

        .el-input {
          margin: 0 6px;

          .el-input__inner {
            //min-width: 100px;
            border: none;
          }
        }
      }
    }

    .el-table {
      th {
        background: #fff !important;
      }

      .inBoundMoney {
        width: 100%;
        text-align: center;
        font-weight: bold;

        span {
          letter-spacing: 15px;
        }
      }
    }
  }

}
</style>
